<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\Check\CheckEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\Check\CheckCmbBankFlow;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPermissionAnchorModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Remote\Rms\RmsShopRemote;
use App\Service\OpenShop\Feishu\MessageSendService;
use App\Service\OpenShop\Feishu\MessageService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\Feishu\ShopTagsService;
use App\Service\OpenShop\User\RmsUserService;
use Guanguans\Notify\Factory;
use Guanguans\Notify\Messages\FeiShu\CardMessage;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Kuafu\Nsq\NsqPublisher;
use Kuafu\Nsq\NsqSubscriber;
use Nsq\Envelope;

class DelOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:del-order {orderNo} {--invalidateType=} {--reason=}  {delAll} ';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '作废订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        // KD2022070455039586
        $orderNo        = $this->argument('orderNo');
        $invalidateType = $this->option('invalidateType') ?? null;
        $reason         = $this->option('reason') ?? "";
        $delAll         = (bool)$this->input->getArgument("delAll");
        if (!$orderNo) {
            dd('orderNo不能为空');
        }

        $signOrder = OpenShopSignOrderModel::query()
                                           ->with(
                                               [
                                                   'baseInfoRel',
                                                   'progressRel'
                                               ])
                                           ->where('orderNo', $orderNo)
                                           ->first();
        if (!$signOrder) {
            dd('找不到订单');
        }

        if ($signOrder->status == SignOrderEnum::ORDER_STATUS_NO) {
            $this->info('订单已废弃，继续往下执行...');
        }



        $signOrder->status          = SignOrderEnum::ORDER_STATUS_NO;
//        $signOrder->dissolveStatus  = OpenShopSignOrderModel::DISSOLVE_STATUS_CLOSE;

        if (!$signOrder->invalidateType) {
            if (empty($invalidateType)) {
                dd('当前作废订单缺少作废类型参数 请传值 --invalidateType');
            }
            $signOrder->invalidateType = $invalidateType;
            if ($invalidateType == OpenShopSignOrderModel::INVALIDATE_TYPE_5) {
                if (empty($reason)) {
                    dd('当前作废订单类型 缺少reason参数');
                }
                $signOrder->invalidedReason = $this->option('reason');
            }
        }
        $signOrder->save();

        // todo 招商流水置为待使用
        if ($signOrder->invalidateType == OpenShopSignOrderModel::INVALIDATE_TYPE_2 || $delAll) {
            CheckCmbBankFlow::query()
                            ->whereIn(
                                'refnbr',
                                OpenShopSignOrderPayHistoryModel::query()
                                                                ->where('orderNo', $orderNo)
                                                                ->where('payChannel',
                                                                    CheckEnum::PAY_CHANNEL_BANK)
                                                                ->where('payNo', '!=', '')
                                                                ->pluck('payNo')
                                                                ->toArray())
                            ->update(['used' => 0]);
        }

        //作废子订单
        $this->invalidChildOrder($signOrder, $delAll);



        OpenShopSiteMissionModel::query()->where('orderNo', $orderNo)->update(['isDeleted' => 1]);
        //OpenShopSiteLocationModel::query()->where('orderNo', $orderNo)->update(['isDeleted' => 1]);

        OpenShopSignOrderPermissionAnchorModel::query()->where('orderNo', $orderNo)
                                              ->update(['orderStatus' => SignOrderEnum::ORDER_STATUS_NO]);

        if ($delAll) {
            OpenShopMainProcessModel::query()
                                    ->where('orderNo', $orderNo)
                                    ->orderBy('id', 'desc')
                                    ->update(['shopId' => 0]);
        }


        // 删除巡店帮扶订单
//        CruiseOrderModel::query()->where('orderNo', $orderNo)->update(['isDeleted' => 1]);

        $this->info($orderNo . '订单已完成废弃');

        $this->fsSend($signOrder);

        // 同步 RMS 禁用门店
        try {
            RmsShopRemote::updateShopFieldById($signOrder->progressRel->shopId, ['status' => 1]);
        } catch (\Exception $exception) {
        }

        // 异步通知订货状态
        $this->sendCloseNsq($signOrder->progressRel->shopId, $signOrder);

        return self::SUCCESS;
    }


    /**
     * 作废子订单
     *
     * @param OpenShopSignOrderModel $signOrderModel
     * @param bool $delAll
     */
    public function invalidChildOrder(OpenShopSignOrderModel $signOrderModel, bool $delAll)
    {
        //作废子订单
        $childLocationOrder = $signOrderModel->mainProcessRel->childLocationOrdersRel;
        if ($childLocationOrder) {
            $childLocationOrder->each(function (OpenShopMainProcessModel $mainProcessModel) use ($delAll, $signOrderModel) {
                Artisan::call(
                    "openShop:del-order",
                    [
                        "orderNo"          => $mainProcessModel->orderNo,
                        "--reason"         => $signOrderModel->invalidedReason,
                        "--invalidateType" => $signOrderModel->invalidateType,
                        "delAll"           => $delAll ? 1 : 0
                    ]
                );

                // 更新迁址单解除合同状态（跟随主单状态）
                OpenShopSignOrderModel::query()->where("orderNo", $mainProcessModel->orderNo)->update([
                    "dissolveStatus" => $signOrderModel->dissolveStatus
                ]);

                $this->fsSend($mainProcessModel->signOrderRel);
            });
        }
    }

    public function fsSend($signOrder)
    {

        $provinceCode     = $signOrder->baseInfoRel->provinceCode;
        $organizationUser = OrganizationManageService::getProvinceInfoByProvinceCode($provinceCode);

        $organizationUser['operationUserFeishuId'] = '';
        if (!empty($organizationUser) && !empty($organizationUser['operationUid'])) {
            $operationUser = RmsUserService::getRmsUserInfoByUserIds($organizationUser['operationUid']);
            if ($operationUser['code'] == 200) {
                $organizationUser['operationUserFeishuId'] = $operationUser['data'][0]['feishuUserId'];
            }
        }

        // 飞书 通知
        // 强制通知人 - xm, 吉连, 风雪, 九月
        $fsSend = ['3fgc8798', '9efgbcdb', '9acce1b7', 'c4dd5156'];
        // 获取当前环境
        if (config('app.env') == 'prod' || config('app.env') == 'pre') {
            if (!empty($organizationUser['operationUserFeishuId'])) {
                $fsSend[] = $organizationUser['operationUserFeishuId']; // 添加省区总
            }

            // 手动设置成生产机器人
            Config::set('feishu.openShop.appID', 'cli_a29222d9e7fc900b');
            Config::set('feishu.openShop.AppSecret', 'pD3Xca1gqECIM1ULslsxAeznpo6eBNuo');

            $fsSend[] = 'fea66474'; // 巴斯
            $fsSend[] = '5dd87136'; // 山治
            $fsSend[] = 'Z000236'; // 烟柔
            $fsSend[] = 'e58f8774'; // 琴酒
            $fsSend[] = '14d48635'; // 蓝兔
        }

        $fs = new MessageSendService();
        $fs->setText('**订单作废解约通知**')
           ->setField('开店单号', $signOrder->orderNo)
           ->setField('门店编号', $signOrder->shopCode)
           ->setField('门店区域', $signOrder->baseInfoRel->chooseShopAddressPrefix)
           ->setField('作废时间', date('Y-m-d H:i:s'))
           ->setField('作废原因', OpenShopSignOrderModel::INVALIDATE_TYPE_TEXT[$signOrder->invalidateType] ?? "")
           ->setField('备注', $signOrder->invalidedReason)
           ->setField('对应省总', $organizationUser['operationName'] ?? '暂无省区总')
           ->setReceiveFeiShuIds($fsSend)
           ->send();

    }

    public function sendCloseNsq($shopId, OpenShopSignOrderModel $signOrderModel)
    {
        (new NsqPublisher(config('nsq.default.address')))
            ->pub('tiger.openShop.shopStatus.switch', [
                'nsqEventTime'   => time(),
                'shopId'         => $shopId,
                'switch'         => 0, // 门店禁用关闭为 0
                'operatorId'     => 0,
                'operatorName'   => '系统',
                'invalidateType' => $signOrderModel->invalidateType,
                'reason'         => $signOrderModel->invalidedReason,
                'operationTime'  => time()
            ]);
    }

}
